<script lang="ts">
import { defineComponent, h, reactive, ref, useAttrs } from "vue";
import {
  NButton,
  useMessage,
  NP,
  NDataTable,
  NModal,
  DataTableProps,
} from "naive-ui";
import axios from "axios";
import { TableProps } from "@/type/TableProps";
import { Rules } from "@/type/rules";
import { DialogProps } from "@/type";
import HModal from "@/components/HModal.vue";
import { useRouter } from "vue-router";

export default defineComponent({
  name: "h-data-table",
  components: {
    NButton,
    NP,
    NDataTable,
    //
    NModal,
    //
    HModal,
  },

  setup() {
    const router = useRouter();
    const {
      value: { fullPath },
    } = router.currentRoute;
    const checkedRowKeysRef = ref<Array<string | number>>([]);
    //定义一个data数组变量接收数据
    const data = ref<any>([]);
    const record = ref();
    const modalShow = ref<boolean>();
    // 是否是添加数据
    const isAdd = ref(true);
    const { dialog, title, columns, service, ...restTableProps } =
      useAttrs() as TableProps;
    const message = useMessage();
    const isQualityTetetion = fullPath.includes("/quality-tetection");

    return {
      restTableProps,
      isAdd,
      checkedRowKeys: checkedRowKeysRef,
      pagination: {
        pageSize: 10,
      },
      modalShow,
      data,
      message,
      title,
      record,
      columns,
      service,
      dialog,
      isQualityTetetion,
    };
  },
  methods: {
    setModalVisible(value: boolean | undefined) {
      if (!value) {
        this.record = ref();
      }
      this.modalShow = value;
    },
    updataRow(row: Rules) {
      console.log("更新数据");
      this.data?.splice(
        this.data?.indexOf(
          this.data?.find((i: { id: number }) => i.id === Number(row.id)) as any
        ),
        1,
        row
      );
    },
    // 新增数据
    adddata(data: Rules) {
      data.id = this.data?.length + 1 ?? 0;
      this.data?.push(data);
    },
    // 删除数据
    deletebtn(ids?: string[] | null) {
      const len = this.checkedRowKeys.length;
      let data: any = [];
      if (ids && ids.length > 0) {
        data = ids;
      } else {
        data = this.checkedRowKeys.map((k) => String(k));
      }
      // 进行数据有效性判断
      if (!data || data.length <= 0) {
        this.message.destroyAll();
        this.message.error("请选择要删除的数据！");
        return;
      }
      try {
        // const { success, message } = await this.service?.remove(data);
        this.service?.remove(data).then(({ success, message }) => {
          if (success) {
            this.message.destroyAll();
            this.message.success(`${message} ${data.length} 条数据`);

            // 遍历所选择删除的列表并查找对应的数据
            for (const id of data) {
              console.log("删除数据下的id===" + id);
              const index = this.data.findIndex(
                (item: { id: number }) => item.id === Number(id)
              );
              console.log("删除数据下的index===" + index); //有疑问
              if (index >= 0) {
                // 从 this.data 中删除该数据，并重新设置表格的 key
                this.data.splice(index, 1);
              }
            }
            // 重新设置表格的 key，并清空已勾选的行
            this.data?.forEach((item: { id: any }, index: number) => {
              item.id = index + 1;
            });
            console.log(this.data);
            this.checkedRowKeys = [];
          } else {
            throw new Error(message);
          }
        });
      } catch (error) {
        this.message.destroyAll();
        this.message.error("删除失败！");
      }
    },
  },

  computed: {
    dialogProps(): DialogProps {
      return {
        ...this.dialog,
        row: this.record,
        title: this.title,
        service: this.service,
        show: this.modalShow ?? false,
        dialogshow: this.setModalVisible,
        columns: this.columns?.filter((c) => !c.hideInForm),
        updataRow: this.updataRow,
        adddata: this.adddata,
      };
    },

    tableProps() {
      const {
        rowKey = "id",
        pagination = {
          pageSize: 10,
        },
        options,
        hiddenBtn,
        otherBtn,
        ...restProps
      } = this.restTableProps;

      const createCloumns = this.columns?.filter(
        (c) => !c.hideInTable
      ) as any[];
      if (typeof options !== "boolean") {
        createCloumns?.push({
          title: "操作",
          width: "180px",
          fixed: "right",
          key: "actions",
          className: "actions",
          render: (row: any) => {
            const Edit = h(
              NButton,
              {
                text: true,
                style: {
                  margin: "0px",
                  padding: "5px 10px",
                  cursor: "pointer",
                },
                onClick: () => {
                  this.record = row;
                  this.setModalVisible(true);
                },
              },
              {
                default: () => "编辑",
              }
            );
            const Enable = h(
              NButton,
              {
                text: true,
                style: {
                  margin: "0px",
                  padding: "5px 10px",
                  cursor: "pointer",
                  color: "#4caf50",
                  borderLeft: "1px solid #d2d1d1",
                },
                value: row.status,
                onClick: () => {
                  row.status = !row.status;
                },
              },
              { default: () => "启动" }
            );
            const Delete = h(
              NButton,
              {
                text: true,
                style: {
                  margin: "0px",
                  color: "#DC143C",
                  borderLeft: "1px solid #d2d1d1",
                  padding: " 5px 10px",
                  cursor: "pointer",
                },
                onClick: () => {
                  // 调用外面传过来的函数
                  // this.delRow(row);
                  this.deletebtn([row.id]);
                },
              },
              { default: () => "删除" }
            );
            // 定义数组存放按钮
            const Btns = [];
            // 如果hiddenBtn为false则显示启动和删除按钮，否则显示otherBtn
            if (!hiddenBtn?.hidden) {
              Btns.push(Edit, Enable, Delete);
            } else {
              Btns.push(otherBtn);
            }
            return [...(Btns ?? [])];
          },
          ...(options || {}),
        });
      }
      return reactive({
        ...restProps,
        rowKey: (row: any) => row[rowKey],
        pagination,
        data: this.data ?? [],
        columns: createCloumns,
      } as DataTableProps);
    },
  },
  // 获取后台数据
  mounted() {
    /*   axios("/api/messages").then((res) => {
      let resData = res.data;
      if (resData.code == 200) {
        const ruleList = resData.data;
        this.data.push(...ruleList);
        console.log("myMock==>", ruleList);
      }
    });
    axios("/api/quality").then((res) => {
      let resData = res.data;
      if (resData.code == 200) {
        const qualityList = resData.data;
        this.data.push(...qualityList);
        console.log("myMock==>", qualityList);
      }
    }); */
    this.service?.page({}).then(({ data, message }) => {
      this.data = data;
      this.data = data?.map((item, index) => ({ key: index + 1, ...item }));
    });
  },
});
</script>
<template>
  <div class="table">
    <div class="rule-title">
      <h3 style="margin-left: 20px;width:100px;">{{ title }}</h3>
      <div class="button">
        <slot name="QualityButton"></slot>
        <slot name="QualityTetectionBtton"></slot>
        <div v-if="!isQualityTetetion">
          <n-button @click="setModalVisible(true)" type="primary"
            >新建</n-button
          >
          <n-button @click="deletebtn()" type="error" ghost>删除</n-button>
        </div>
        <!-- <slot
          name="newFolder"
          @click="setModalVisible(true)"
          type="primary"
        ></slot>
        <slot name="delete" @click="deletebtn()" type="error" ghost></slot> -->
      </div>
    </div>
    <h-modal v-bind="dialogProps"></h-modal>
    <n-data-table
      v-bind="tableProps"
      :scroll-x="1500"
      v-model:checked-row-keys="checkedRowKeys"
    />
  </div>
</template>
<style lang="less" scoped>
.table {
  background-color: #ffffff;
  margin-left: 10px;
  margin-top: 20px;
  margin-right: 24px;
  .rule-title {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    text-align: center;
    .n-p {
      line-height: 38px;
      margin: auto 0;
      margin-left: 10px;
      font-size: 17px;
    }
    .button {
      width: 250px;
      /* 两端对齐 */
      display: flex;
      align-items: center;

      .n-button {
        margin-right: 10px;
      }
    }
  }
}
.table .rule-title .button[data-v-e7f6379a]{
  width:100%;
  justify-content:flex-end;
}
:deep(.actions) {
  text-align: center;
}
</style>
